//
//  MYGMapMenuController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/13.
//

import UIKit
import SnapKit

class MYGMapMenuController: MYGBaseController {
    // MARK: - content
    private var content: [MYGMapPositionModel] = [] {
        didSet {
            selIndex = 0
            tableView.reloadData()
        }
    }
    
    private var selIndex: Int = 0 {
        didSet {
            tableView.reloadData()
        }
    }
    
    var sendAction: ((MYGMapPositionModel) -> Void)?
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
    }

    // MARK: - UI
    private func configUI() {
        title = "位置"
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        view.addSubview(mapView)
        mapView.addSubview(positionImageView)
        view.addSubview(searchView)
        searchView.addSubview(textField)
        view.addSubview(tableView)
        
        mapView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(searchView.snp.top)
        }
        
        searchView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(tableView.snp.top)
            make.height.equalTo(43)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(210)
        }
        
        textField.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(10)
            make.bottom.equalToSuperview()
            make.height.equalTo(30)
        }
        
        positionImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    // MARK: - lazy load
    private lazy var mapView: BMKMapView = {
        let mapView = BMKMapView()
        mapView.delegate = self
        mapView.zoomLevel = 15
        return mapView
    }()

    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: MYGMapPositionCell.self)
        return tableView
    }()

    private lazy var searchView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var textField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(14)
        tf.textColor = .rgba(51, 51, 51)
        
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.image(UIImage(named: "Common/search"))
            confer.text(" 搜索地点")?.font(.regular(14)).textColor(.rgba(163, 163, 163, 1))
        })
        
        tf.textAlignment = .center
        
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 2
        
        tf.addTarget(self, action: #selector(textFieldValueChanged), for: .editingChanged)
        return tf
    }()
    
    private lazy var locationManager: BMKLocationManager = {
        let manager = BMKLocationManager()
        manager.delegate = self
    
        return manager
    }()
    
    private lazy var positionImageView: UIImageView = {
        let imgV = UIImageView(image: UIImage(named: "Map/location"))
        return imgV
    }()
    
    private lazy var searchManager: BMKPoiSearch = {
        let manager = BMKPoiSearch()
        manager.delegate = self
        return manager
    }()
    
    private lazy var sendButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(.rgba(255, 9, 9, 1), for: .normal)
        btn.titleLabel?.font = .regular(13)
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
}

extension MYGMapMenuController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        content.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        74
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGMapPositionCell.self, for: indexPath)
        cell.model = content[indexPath.row]
        cell.selectImageView.isHidden = !(indexPath.row == selIndex)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selIndex = indexPath.row
    }
}

extension MYGMapMenuController {
    private func startOnceLocation() {
        locationManager.requestLocation(withReGeocode: false, withNetworkState: true) {[weak self] location, state, error in
            if let error = error {
                print("定位失败：\(error)")
                return
            }
            
            if let location = location {
                if let coor = location.location?.coordinate {
                    self?.mapView.setCenter(coor, animated: false)
                }
            }
        }
    }
    
    private func searchPoi() {
        var text = textField.text ?? ""
        if text.isEmpty {
            text = "建筑"
        }
        let coor = mapView.centerCoordinate
        
        let nearOption = BMKPOINearbySearchOption()
        nearOption.keywords = [text]
        nearOption.location = coor
        nearOption.radius = 1000000
        searchManager.poiSearchNear(by: nearOption)
    }
}

extension MYGMapMenuController: BMKMapViewDelegate {
    func mapViewDidFinishLoading(_ mapView: BMKMapView) {
        self.startOnceLocation()
    }
    
    func mapView(_ mapView: BMKMapView, regionDidChangeAnimated animated: Bool) {
        textField.text = ""
        self.searchPoi()
    }
}

extension MYGMapMenuController: BMKLocationManagerDelegate {
    
}

extension MYGMapMenuController: BMKPoiSearchDelegate {
    func onGetPoiResult(_ searcher: BMKPoiSearch!, result poiResult: BMKPOISearchResult!, errorCode: BMKSearchErrorCode) {
        guard errorCode == BMK_SEARCH_NO_ERROR else {
            print("检索失败：\(errorCode)")
            return
        }
        
        let result = poiResult.poiInfoList
        content = []
        content = poiResult.poiInfoList.map({ item in
            let model = MYGMapPositionModel()
            model.model = item
            model.name = item.name
            let point1 = mapView.centerCoordinate
            let point2 = item.pt
            let distance = Int(BMKMetersBetweenCoordinates(point1, point2))
            var text = ""
            if distance <= 100 {
                text = "100m内"
            } else if distance > 100 && distance < 1000 {
                text = "\(distance)m"
            } else {
                text = String(format: "%.2fkm", CGFloat(distance)/1000)
            }
            model.hint = "\(text) | \(item.address ?? "")"
            
            return model
        })
    }
}

extension MYGMapMenuController {
    @objc
    private func textFieldValueChanged() {
        searchPoi()
    }
    
    @objc
    private func clickButton(_ btn: UIButton) {
        guard content.count > 0 else {
            MMYGHUD.showToast(text: "位置获取失败")
            return}
        if btn == sendButton {
            sendAction?(content[selIndex])
            self.navigationController?.popViewController()
        }
    }
}
